package com.cunyme;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.app.Activity;
import android.app.LocalActivityManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;


/****************************
 * 
 * Eventually, you will add the option to select announcements for day, week, month, or all.
 * And copyright at the bottom.
 ***************************/



public class Blackboard_announcements extends Activity {
	@Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        
		SQLiteDatabase cuny_meDB = openOrCreateDatabase("cuny_me.db", Context.MODE_PRIVATE, null);
        helper_functions helpers = new helper_functions();
		final Map <String, String> blackboard_cookies = helpers.getcookies("blackboard", cuny_meDB);
		cuny_meDB.close();
        // In this page, we are creating a layout of buttons based on the user's class schedule.  Because this is dynamic,
        // we create the layout here, as opposed to in an xml file.
        
        // This creates the main layout...
    	ScrollView announcements_layout = new ScrollView(this);
    	announcements_layout.setBackgroundColor(0xffffffff);
    	LinearLayout child_layout = new LinearLayout(this); 
    	/*announcements_layout.setLayoutParams(new LayoutParams(
	            LayoutParams.WRAP_CONTENT,
	            LayoutParams.WRAP_CONTENT));
;*/
    	child_layout.setOrientation(LinearLayout.VERTICAL);
    	child_layout.setBackgroundColor(0xffffffff);
    	LinearLayout.LayoutParams bboard_params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
    			LinearLayout.LayoutParams.WRAP_CONTENT); 
		announcements_layout.addView(child_layout);
		try
		{
			Connection announcements_conn = Jsoup.connect("https://bbhosted.cuny.edu/bin/common/announcement.pl").data("action","LIST", "time", getIntent().getExtras().getString("time"), "context", "course_entry", "course_id", getIntent().getExtras().getString("course_id"), "render_type", "DEFAULT").cookie("JSESSIONID", blackboard_cookies.get("JSESSIONID")).cookie("session_id", blackboard_cookies.get("session_id")).cookie("ObSSOCookie", blackboard_cookies.get("ObSSOCookie")).cookie("NSC_100211.qspe2_wjq2:443", blackboard_cookies.get("NSC_100211.qspe2_wjq2:443")).cookie("BIGipServerbbhosted_ssl_pl", blackboard_cookies.get("BIGipServerbbhosted_ssl_pl"));
			org.jsoup.nodes.Document announcements_doc = announcements_conn.timeout(10*1000).post();
			String announcements_html = announcements_doc.html();
			
			String[] ann_str_manip_1 = announcements_html.split("<!-- ### DO NOT DELETE THIS ROW: LOCKING WIDTHS TABLE ROW ### -->");
			String[] ann_str_manip = ann_str_manip_1[1].split("END ANNOUNCEMENT BLOCK");
			ann_str_manip = ann_str_manip[0].split("<!-- BEGIN ANNOUNCEMENT DIVIDER -->");
			for (int i = 0; i < ann_str_manip.length; i++)
			{	
				ann_str_manip[i] = ann_str_manip[i].replaceFirst("<b>", "<b>cockadoodledoo");
				ann_str_manip[i] = ann_str_manip[i].replaceAll("Posted by:", "\nPosted by:");
				String[] indiv_ann = ann_str_manip[i].split("<b>cockadoodledoo");
				indiv_ann[1] = indiv_ann[1].replaceFirst("</b>", "</b>cockadoodledoo");
				final String[] indiv_ann_elements = indiv_ann[1].split("</b>cockadoodledoo");
				
				indiv_ann_elements[0] = indiv_ann_elements[0].replaceAll("<.*?>", "");
				TextView ann_title = new TextView(this);
				ann_title.setText(indiv_ann_elements[0]);
				ann_title.setId(i);
				ann_title.setTypeface(Typeface.DEFAULT_BOLD);
				ann_title.setLayoutParams(bboard_params);
				ann_title.setTextColor(0xff000000);
				child_layout.addView(ann_title);
				
				indiv_ann_elements[1] = indiv_ann_elements[1].replaceAll("<a", "gobblegobblegobblezzz");
				indiv_ann_elements[1] = indiv_ann_elements[1].replaceAll("</a", "commacommacommazzz");
				indiv_ann_elements[1] = indiv_ann_elements[1].replace("</p>", "<br /><br />");
				indiv_ann_elements[1] = indiv_ann_elements[1].replaceAll("<br />", "kookookoozzz");
				indiv_ann_elements[1] = indiv_ann_elements[1].replace("<!--[if gte mso", "onetwobucklemyshoe");
				indiv_ann_elements[1] = indiv_ann_elements[1].replace("<![endif]-->", "threefourclosethedoor");
				indiv_ann_elements[1] = indiv_ann_elements[1].replaceAll("<.*?>", "");
				indiv_ann_elements[1] = indiv_ann_elements[1].replace("onetwobucklemyshoe", "<!--[if gte mso");
				indiv_ann_elements[1] = indiv_ann_elements[1].replace("threefourclosethedoor", "<![endif]-->");
				indiv_ann_elements[1] = indiv_ann_elements[1].replaceAll("kookookoozzz", "<br />");
				indiv_ann_elements[1] = indiv_ann_elements[1].replaceAll("gobblegobblegobblezzz", "<a");
				indiv_ann_elements[1] = indiv_ann_elements[1].replaceAll("commacommacommazzz", "</a");
				indiv_ann_elements[1] = indiv_ann_elements[1] + "<br />";
				
				final String[] content_part_components = indiv_ann_elements[1].split("<a hr");
				for (int j = 0; j < content_part_components.length; j++)
				{
					TextView ann_content = new TextView(this);
					child_layout.addView(ann_content);
					if (content_part_components[j].indexOf("ef=") >= 0)
					{
						content_part_components[j] = "<a hr" + content_part_components[j];
						if (content_part_components[j].indexOf("@@") >= 0)
						{
							final String content_component = content_part_components[j];
							String[] pre_post_link = content_component.split("</a>");
							String link_name = pre_post_link[0].replaceAll("<.*?>", "");
							SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
							stringBuilder.append(link_name);
							stringBuilder.setSpan(
									new ClickableSpan()
									{
										@Override
										public void onClick(View widget)
										{
											String[] string_manip = content_component.split("ef=");
											string_manip = string_manip[1].split("\">");
											String url_string = string_manip[0].replace("\"", "https://bbhosted.cuny.edu");
											Intent download_file = new Intent(Blackboard_announcements.this, Download_helper.class);
											download_file.putExtra("url", url_string);
											startActivity(download_file);
										}
									},
									0, link_name.length(),
									Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
							ann_content.setText(stringBuilder);
							
							TextView left_over = new TextView(this);
							left_over.setText(Html.fromHtml(pre_post_link[1]));
							left_over.setMovementMethod(LinkMovementMethod.getInstance());
							left_over.setId(i + 500);
							left_over.setLayoutParams(bboard_params);
							left_over.setTextColor(0xff000000);
							child_layout.addView(left_over);
						}
						else if (content_part_components[j].indexOf("content_id") >= 0)
						{
							final String content_component = content_part_components[j];
							final String[] pre_post_link = content_component.split("</a>");
							String link_name = pre_post_link[0].replaceAll("<.*?>", "");

							SpannableStringBuilder stringBuilder = new SpannableStringBuilder();
							stringBuilder.append(link_name.trim());
							stringBuilder.setSpan(
									new ClickableSpan() {
										@Override
										public void onClick(View widget)
										{
											String [] manip = pre_post_link[0].split("<a href=\"");
											manip = manip[1].split("\">");
											String ann_url = "http://bbhosted.cuny.edu" + manip[0];
												String[] string_manip = ann_url.split("ann_id=");
												string_manip = string_manip[1].split("&");
												String ann_id = string_manip[0].trim();
												Intent gotoContentPage = new Intent(Blackboard_announcements.this, Blackboard_content_page.class);
												gotoContentPage.putExtra("course_id", getIntent().getExtras().getString("course_id"));
												gotoContentPage.putExtra("is_ann", "yes");
												gotoContentPage.putExtra("ann_id", ann_id);
												startActivity(gotoContentPage);
										}
									},
									0, link_name.trim().length(),
									Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
							ann_content.setText(stringBuilder);
							
							TextView left_over = new TextView(this);
							left_over.setText(Html.fromHtml(pre_post_link[1]));
							left_over.setMovementMethod(LinkMovementMethod.getInstance());
							left_over.setId(i + 500);
							left_over.setLayoutParams(bboard_params);
							left_over.setTextColor(0xff000000);
							child_layout.addView(left_over);	
						}
						else
							ann_content.setText(Html.fromHtml(content_part_components[j]));
					}
					else
						ann_content.setText(Html.fromHtml(content_part_components[j]));
					ann_content.setMovementMethod(LinkMovementMethod.getInstance());
					ann_content.setId(i + 500);
					ann_content.setLayoutParams(bboard_params);
					ann_content.setTextColor(0xff000000);

				}
			}
		    setContentView(announcements_layout);
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			Toast.makeText(getApplicationContext(), "Unable to Establish Connection.  Please try again.", Toast.LENGTH_SHORT).show();	
			finish();
		}
    }
	public boolean onCreateOptionsMenu(Menu menu)
	{
		super.onCreateOptionsMenu(menu);
		
		menu.add(0, Menu.FIRST, Menu.NONE, "View Today");
		menu.add(0, Menu.FIRST+1, Menu.NONE, "View Last 7 Days");
		menu.add(0, Menu.FIRST+2, Menu.NONE, "View Last 30 Days");
		menu.add(0, Menu.FIRST+3, Menu.NONE, "View All");

		
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
	    // Handle item selection
		
	    switch (item.getItemId()) {
	    case Menu.FIRST:
			Intent gotoAnnouncements_day = new Intent(Blackboard_announcements.this, Blackboard_announcements.class);
			gotoAnnouncements_day.putExtra("course_id", getIntent().getExtras().getString("course_id"));
 		 	gotoAnnouncements_day.putExtra("time", "today");
 			startActivity(gotoAnnouncements_day);
	    	finish();
	        return true;
	    case Menu.FIRST+1:
			Intent gotoAnnouncements_week = new Intent(Blackboard_announcements.this, Blackboard_announcements.class);
			gotoAnnouncements_week.putExtra("course_id", getIntent().getExtras().getString("course_id"));
 		 	gotoAnnouncements_week.putExtra("time", "week");
 			startActivity(gotoAnnouncements_week);
	    	finish();
	        return true;
	    case Menu.FIRST+2:
			Intent gotoAnnouncements_month = new Intent(Blackboard_announcements.this, Blackboard_announcements.class);
			gotoAnnouncements_month.putExtra("course_id", getIntent().getExtras().getString("course_id"));
 		 	gotoAnnouncements_month.putExtra("time", "month");
 			startActivity(gotoAnnouncements_month);
	    	finish();
	        return true;
	    case Menu.FIRST+3:
			Intent gotoAnnouncements_all = new Intent(Blackboard_announcements.this, Blackboard_announcements.class);
			gotoAnnouncements_all.putExtra("course_id", getIntent().getExtras().getString("course_id"));
 		 	gotoAnnouncements_all.putExtra("time", "all");
 			startActivity(gotoAnnouncements_all);
	    	finish();
	        return true;
	    default:
			Toast.makeText(getApplicationContext(), "Oh, dear.  Something went wrong.", Toast.LENGTH_SHORT).show();	
			finish();
			return true;
	    }
	}
}
